<?php
namespace App\Repos;

use App\Models\UserEnvelope;
use App\Models\ShopEnvelope;
use App\Models\Order;
use App\Services\WechatTpl;
use DB,Log;

class UserEnvelopeRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$list = UserEnvelope::select(['id','shop_id','coupon_id','end_date'])->with('coupon:id,name,valid_days,value,min_amount')->with('shop:id,name')->where($where)->paginate($num); 	  	
	  	return $list;     
	}

	/**
	 * 拍十秒中奖或者订单返现的红包
	 * 
	 */
	public static function create($data)
	{		
		$rs['status'] = false;
		try {
			DB::beginTransaction();
			$openid = array_pull($data,'openid');
			$type = array_pull($data,'type');
			// 订单完成返利
			if($type==2) {
				UserEnvelope::create($data);	
			}
			
			$where['id']           = $data['shop_envelope_id'];
			$seData['user_id']     = $data['user_id'];
			$seData['snatched_at'] = date('Y-m-d H:i:s');
			$seData['is_snatched'] = 1;
			ShopEnvelope::where($where)->update($seData);	
			
			$moneyData['user_id'] = $data['user_id'];
			$moneyData['money']   = $data['money'];
			$moneyData['shop_id'] = $data['shop_id'];
			$moneyData['type']    = $type; 
			UserMoneyLogRepo::create($moneyData);

			//如果有订单 那么订单的拍十秒要修改 1为以参加过
			if(array_get($data,'order_code')) {
				$order = Order::where('code',$data['order_code'])->first();
				$order->tenseconds = 1;
				$order->save();	
			}
			

			// 调用发红包接口
			//dd($data);
			$flag = WechatTpl::toBalance($data,$openid);
			Log::info('红包发送结果'.json_encode($flag));
			if($flag['result_code']=='FAIL') {
				Log::info('红包发送失败'.$flag['err_code_des']); 
			// 	return $rs;	
			}
			DB::commit();
			$rs['status'] = true;
			return $rs; 						
			
		} catch (\Exception $e) {
			DB::rollback();
			$rs['msg'] = $e->getMessage();
			Log::info('69行，红包发送失败：'.$e->getMessage());
			return $rs;
		}
		
		return $rs;		
	}

	public static function find($where)
	{
		return ShopEnvelope::with('coupon')
							->where($where)
							->first();
	} 

	public static function update($where,$data)
	{
		return ShopEnvelope::where($where)->update($data);
	}

	
	
	
	

	
	
	
}